import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-bill-details',
  templateUrl: './bill-details.component.html'
})
export class BillDetailsComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  deviceId: string = '' //查询deviceId
  carNumber: string = '' //查询车牌号码

  tableSearch: any = {
    companyId: '',
    companyName: '',
    deviceId: '',
    projectName: '',
    username: '',
    billType: '',
    dataSource: '',
    startTime: '',
    endTime: ''
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
      if (common.getCookie('jumpTo/system/bill-details')) {
        const jumpData = JSON.parse(common.getCookie('jumpTo/system/bill-details'))
        common.clearCookie('jumpTo/system/bill-details')
        this.tableSearch.companyId = jumpData.companyId
        this.tableSearch.companyName = jumpData.companyName
        this.tableSearch.billType = jumpData.billType
        this.tableSearch.startTime = jumpData.startTime || ''
        this.tableSearch.endTime = jumpData.endTime || ''
        this.initDate()
      }
    })
  }

  specifyId = {
    picker1: 'datetimepicker3',
    picker2: 'datetimepicker4'
  }

  // 时间选择回调
  dateSelect(time) {
    this.tableSearch.startTime = time.startTime
    this.tableSearch.endTime = time.endTime
  }

  // 初始化1天的时间
  initDate() {
    this.specifyTime = {
      startTime: this.tableSearch.startTime,
      endTime: this.tableSearch.endTime
    }
  }
  specifyTime: any

  //初始化车辆
  selectCompany() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        var that = this
        $('#carNumberSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
            ajax: {
              url: config.BaseURL + 'stats/carListByCarNumber.html',
              dataType: 'json',
              delay: 50,
              method: 'POST',
              xhrFields: { withCredentials: true },
              data: function (params) {
                return {
                  carNumber: params.term // search term
                }
              },
              processResults: function (data, params) {
                var options = new Array()
                // 小于10个数量才判断重复
                if (data.data.length <= 10) {
                  let arr = []
                  let sameCar = []
                  // 判断相同的车牌号
                  for (let index = 0; index < data.data.length; index++) {
                    let car = data.data[index]
                    if (arr.indexOf(car.carNumber) != -1) {
                      sameCar.push(car.carNumber)
                    } else {
                      arr.push(car.carNumber)
                    }
                  }
                  $(data.data).each(function (index, car) {
                    if (sameCar.indexOf(car.carNumber) != -1) {
                      options.push({
                        id: car.deviceId,
                        text: car.carNumber + '[' + car.parentName + ']'
                      })
                    } else {
                      options.push({
                        id: car.deviceId,
                        text: car.carNumber
                      })
                    }
                  })
                } else {
                  $(data.data).each(function (index, car) {
                    options.push({
                      id: car.deviceId,
                      text: car.carNumber
                    })
                  })
                }
                return {
                  results: options //获取查询后的结果
                }
              },
              cache: true
            },
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.deviceId = data.id
            if (data.text.indexOf('[') > 0) {
              that.carNumber = data.text.split('[')[0]
            } else {
              that.carNumber = data.text
            }
          })
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  //清除车辆选中值
  del_carNumber() {
    this.deviceId = ''
    this.carNumber = ''
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#carNumberSelect2').val('')
    $('#select2-carNumberSelect2-container').empty()
    $('#select2-carNumberSelect2-container').attr('title', '')
    $('#select2-carNumberSelect2-container').prepend(str)
  }

  changeBillType() {
    this.load()
  }
  changeDataSource() {
    this.load()
  }

  //公司[项目]选中回调
  companySelected(data) {
    this.tableSearch.companyId = data.companyId
    this.tableSearch.companyName = data.companyName
  }

  ngOnInit() {
    this.load()
    this.selectCompany()
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        carNumber: this.carNumber,
        companyId: this.tableSearch.companyId,
        companyName: this.tableSearch.companyName,
        deviceId: this.tableSearch.deviceId,
        projectName: this.tableSearch.projectName,
        username: this.tableSearch.username,
        billType: this.tableSearch.billType,
        dataSource: this.tableSearch.dataSource,
        startTime: this.tableSearch.startTime,
        endTime: this.tableSearch.endTime
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('renewalBill/pageList.html', reqdata).subscribe(res => {
      const data = res.data
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
}
